package com.lollipop.rabbitmq.eight;

import com.lollipop.rabbitmq.util.RabbitMqUtiils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @Author: Lollipop
 * @Date: 2021-10-06 17:02
 * @Description: 死信队列
 */
public class Consumer01 {
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    public static final String DEAD_EXCHANGE = "dead_exchange";
    public static final String NORMAL_QUEUE = "normal_queue";
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMqUtiils.getChannel();

        // 声明交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", "world");
        // 死信条件-2.设置队列最大长度，超过最大长度的消息变为死信
        /*arguments.put("x-max-length", 6);*/

        // 声明队列
        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);

        // 绑定队列、交换机
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "hello");
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "world");
        // 死信条件-2.设置队列最大长度，超过最大长度的消息变为死信
        /*DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println("消费者Consoumer01接收到的消息：" + new String(message.getBody(), StandardCharsets.UTF_8) + "routingkey:" + message.getEnvelope().getRoutingKey());
        };*/

        // 死信条件3-消息被拒绝
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody());
            if ("message5".equals(msg)) {
                System.out.println("消息" + msg + "被拒绝，将成为死信");
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("消费者Consoumer01接收到的消息：" + new String(message.getBody(), StandardCharsets.UTF_8) + "routingkey:" + message.getEnvelope().getRoutingKey());
                // 手动应答，不批量应答
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        };
        // 死信条件1、2
        /*channel.basicConsume(NORMAL_QUEUE, true, deliverCallback, consumerTag -> {
        });*/
        // 死信条件3
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, consumerTag -> {
        });
    }
}
